package com.midian.common.filter;
 
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.midian.model.common.vo.RequestVo;

public class EscapeFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//设置中文编码 
		request.setCharacterEncoding("utf-8");
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		String contextPath = httpRequest.getContextPath();
		//判断请求路径
		String requestURI = httpRequest.getRequestURI();
		String html =requestURI.substring(requestURI.lastIndexOf(".")+1);
		if("html".equals(html)){
			   chain.doFilter(request, response);
				  return ;
		}
		if(requestURI.equals(contextPath+"/mc/qualityReportsaveRunReportStepOne")){
		    chain.doFilter(request, response);
		  return ;
		}
		if(requestURI.equals(contextPath+"/mc/qualityReportsaveRunReportStepTwoFtp")){
		    chain.doFilter(request, response);
		  return ;
		}
		if(requestURI.equals(contextPath+"/mc/qualityReportopenReportByAtab")){
			    chain.doFilter(request, response);
			  return ;
		}
	   Map<String,String[]> readMap = 	httpRequest.getParameterMap();
	   Map<String,String[]> writMap = new HashMap<String, String[]>();
	    writMap.putAll(readMap);
	  
	    for (String key : writMap.keySet()) {
			Object ob =  writMap.get(key);
			if(ob!=null){
				if(ob instanceof String[] && !key.equals("password")){
					String[] obs =  (String[]) ob; 
					for (int i = 0; i < obs.length; i++) {
						 if(obs[i]!=null){
							//  //System.out.println("key=="+key +"   请求参数为数组===="+obs[i]);
							  String str = obs[i]+"";
								str = str.replaceAll("&", "&amp;");
								str = str.replaceAll("<", "&lt;");
								str = str.replaceAll(">", "&gt;");
								str = str.replaceAll("\"", "&quot;");    
							  obs[i] = str;
						 }
					 }
					  writMap.put(key, obs);
				} 
			} 
			
		}
	    RequestVo vo = new RequestVo(httpRequest,writMap);
	    chain.doFilter(vo, response);
	    return ;
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		 
	}
}
